<template>
  <div class="head">
    <div class="logo" @click="jumpProduct">
      <img :src="state.logoSrc" style="width: 150px" class="logoImg" />
    </div>
    <div class="env">
      <span>当前环境：</span>
      <a-select
      v-model:value="state.currEnvId"
      style="border-color: transparent;width: 100px;"
      :options="state.envs"
      @change = "changeEnvId(item)"
    ></a-select>
    </div>
    <a-select
      v-model:value="keyword"
      show-search
      placeholder="查找应用"
      :default-active-first-option="false"
      :show-arrow="false"
      :filter-option="false"
      not-found-content="未匹配到相关数据"
      :options="state.searchData"
      @search="searchModule"
      @change="clickModule"
      @blur="keywordBlur"
      class="select"
    ></a-select>
    <a-dropdown class="loginInfo">
      <a @click.prevent> 欢迎 {{ state.nickname}}<DownOutlined class="down-icon"/></a>
      <template #overlay>
        <a-menu>
          <a-menu-item>
            <a @click="loginOut"><login-outlined style="margin-right:5px" />退出登录</a>
          </a-menu-item>
        </a-menu>
      </template>
    </a-dropdown>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref } from "vue";
import { DownOutlined, LoginOutlined } from '@ant-design/icons-vue'
import { reactive } from "@vue/reactivity";
import store from "@/store";
import { envApi, fuzzySearchApi, projectApi } from "@/api/devcloudApi";
import { useRoute, useRouter } from "vue-router";
import { loginApi } from "@/api/commonApi";
import { clearLoginCache, getLocal } from "@/util/utils";
import { message } from "ant-design-vue";
import { setEnvId } from "@/util/devcloudUtils";

export default defineComponent({
  name: "topHeader",
	components: {DownOutlined,LoginOutlined},
  setup() {
    const route = useRoute();
    const router = useRouter()
    const keyword = ref<undefined|string>(undefined)
    const state:any = reactive({
			nickname: '',
      logoSrc: require("../../../static/logo1.png"),
      currEnvId: '',
      envs: [
      ],
      searchData: [],
    });


		const account:any = getLocal('account')
		state.nickname = account.nickname

    const changeEnvId = () => {
      const envId = store.getters.getCurrInfo.envId;
      if (envId === state.currEnvId) {
        return;
      }

      store.commit("setCurrInfo", { envId: state.currEnvId });
      store.commit("toFlush", 'env-'+ state.currEnvId);
    }

    const searchKeyword = async (keyword: string) => {
      if (!keyword) {
        state.searchData = [];
        return;
      }
      const res = await fuzzySearchApi.list(keyword);
      if (res.success) {
        state.searchData = res.result;
      }
    }

    const searchModule = (keyword: string) => {
      searchKeyword(keyword);
    }


    store.watch((state, getters)=>{
      return getters.getCurrInfo.envId
    }, (newVal:string, oldVal:string)=>{
      if(newVal != state.currEnvId){
        state.currEnvId = newVal
        store.commit("toFlush", 'env-'+ state.currEnvId);
      }
    })

    const keywordBlur = () => {
      keyword.value = undefined
    }

    const clickModule = async (moduleId:any) => {
      keyword.value = ''
      if('/publish/product' === route.path){
        const res = await projectApi.getByModuleId(moduleId)
        if(res.success){
          const project = res.result
          store.commit('setCurrInfo', {'productId' : project.productId, 'env' : project.envId, 'projectId': project.id, 'moduleId': moduleId})
          router.push({path: "/publish/project"})
        }
        return
      }
      store.commit("toFlush", parseInt(moduleId));
    }

    const jumpProduct = () => {
        router.push({path: "/publish/product"})
    }
    
		const loginOut = async() =>{
			const res = await loginApi.out()
			if(res.success){
				clearLoginCache()
				router.push({path:'/login'})
			}
		}

    const listEnv = async () => {
      const res = await envApi.list({})
      if(res.success){
        state.envs = []
        const envId = store.getters.getCurrInfo.envId
        let currEnvId = undefined
        res.result.forEach((e:any) => {
          state.envs.push({
            label: e.env,
            value: e.id
          })
          if(envId === e.id){
            currEnvId = e.id
            state.currEnvId = envId
          }
        });
        if(!currEnvId && state.envs.length > 0){
          const envId = state.envs[0].value
          setEnvId(envId)
          store.commit('setCurrInfo', {'envId': envId})
        }
      }
    }

    listEnv()

    return {
      state,
      changeEnvId,
      searchModule,
      clickModule,
      jumpProduct,
      loginOut,
      keyword,
      keywordBlur,
    }
  },
});
</script>


<style lang="less" scoped>
.head {
  justify-content: space-between;
  line-height: 60px;
  display: flex;
  align-items: center;
  border-bottom: 1px solid #6666;

  .select {
    width: 300px;
    border: 1px solid #40a9ff;
    position: absolute;
    left: 70%;
    // transform: translateX(-50%);
    text-align: start;
  }

  .env {
    position: absolute;
    left: 10%;
    a {
      display: inline-block;
    }
  }

  .loginInfo{
    margin-right: 50px;
  }

  .logo {
    cursor: pointer;
    margin-left: 10px;
  }
}
</style>